<?php

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0,$adv=false) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if($adv){
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];
        }
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
/**
 * CURL请求
 * @param $url 请求url地址
 * @param $method 请求方法 get post
 * @param null $postfields post数据数组
 * @param array $headers 请求header信息
 * @param bool|false $debug  调试开启 默认false
 * @return mixed
 */
function httpRequest($url, $method="GET", $postfields = null, $headers = array(), $debug = false) {
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if($ssl){
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "=====post data======\r\n";
        var_dump($postfields);
        echo "=====info===== \r\n";
        print_r($requestinfo);
        echo "=====response=====\r\n";
        print_r($response);
    }
    curl_close($ci);
    return $response;
    //return array($http_code, $response,$requestinfo);
}

/**
 * 过滤数组元素前后空格 (支持多维数组)
 * @param $array 要过滤的数组
 * @return array|string
 */
function trim_array_element($array){
    if(!is_array($array))
        return trim($array);
    return array_map('trim_array_element',$array);
}

function urlsafe_b64encode($string)
{
    $data = base64_encode($string);
    $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
    return $data;

}

function t(){
    echo 1334;
}

/**
 * 对象 转 数组
 * @param object $obj 对象
 * @return array
 */
function object_to_array($obj) {
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }
    return $obj;
}

/**
 * 数组转对象
 * @param array $arr
 */
function array_to_Object($arr){
    if(is_array($arr)){
        return (object) array_map(__FUNCTION__, $arr);
    }else{
        return $arr;
    }
}
/**
 * 检测会员
 * @param bool|false $is_encryption
 * @return array
 */
function checkMember($member_id){
    if($member_id < 1) return false;
    $where = array('id' => $member_id,'status'=>1);
    $member = db('member')->where($where)->find();
    if(empty($member)) return false;
    if($member['status'] == 0) return false;
    return $member;
}

/**
 * 添加图片URL
 * @param bool|false $is_encryption
 * @return array
 */
function getImageUrl($root,$value)
{
    if(!empty($value)) return __ROOT__ . '/static/'.$root .'/'.str_replace('\\',"/",$value);
}
/**
 * 添加图片URL
 * @param bool|false $is_encryption
 * @return array
 */
function getUploadsUrl($value)
{
    if(!empty($value)) return __ROOT__ . '/static/uploads/'.str_replace('\\',"/",$value);
}

/**
 * 搜数据库多条
 * 
 */
function getSelect($model,$field,$where)
{
    $select = db($model)->where("$field=$where")->select();
	return $select;
}
/**
 * 搜数据库单条
 * 
 */
function getInfo($model,$field,$where)
{
    $find = db($model)->where("id=$where")->column($field);
	if(!empty($find)){
		return $find[0];
	}else{
		return '';
	}
	
}

/**
 * 模型所有对象数据转数组
 * @param object $obj
 */
function modelObjectToArray($obj){
    if(empty($obj)) return array();
    $data = array();
    foreach($obj as $g){
        $data[] = $g->toArray();
    }
    return $data;
}
/**
 * 截取字符串
 * 
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
    if(function_exists("mb_substr")){
        $slice= mb_substr($str, $start, $length, $charset);
    }elseif(function_exists('iconv_substr')) {
        $slice= iconv_substr($str,$start,$length,$charset);
    }else{
        $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
        $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
        $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
        $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }    
        $fix='';
        if(strlen($slice) < strlen($str)){
            $fix='';
        }
        return $suffix ? $slice.$fix : $slice;
}


/**
 *    订单排版处理demo
 */
function order_print($arr,$A,$B,$C,$D)
{   
    $orderInfo = '';
    $orderInfo .= '名称           单价  数量 金额<BR>';
    $orderInfo .= '--------------------------------<BR>';
    foreach ($arr as $k5 => $v5) {
    $spec_name = '';
    if(!empty($v5['spec_name'])){
        $spec_name = " ({$v5['spec_name']})";
    }

    $name = $v5['title'].$spec_name;
    $price = $v5['price'];
    $num = $v5['num'];
    $prices = $v5['price']*$v5['num'];
    $kw3 = '';
    $kw1 = '';
    $kw2 = '';
    $kw4 = '';
    $str = $name;
    $blankNum = $A;//名称控制为14个字节
    $lan = mb_strlen($str,'utf-8');
    $m = 0;
    $j=1;
    $blankNum++;
    $result = array();
    for ($i=0;$i<$lan;$i++){
      $new = mb_substr($str,$m,$j,'utf-8');
      $j++;
      if(mb_strwidth($new,'utf-8')<$blankNum) {
        if($m+$j>$lan) {
          $m = $m+$j;
          $tail = $new;
          $lenght = iconv("UTF-8", "GBK//IGNORE", $new);
          $k = $A - strlen($lenght);
          for($q=0;$q<$k;$q++){
            $kw3 .= ' ';
          }
          $tail .= $kw3;
          break;
        }else{
          $next_new = mb_substr($str,$m,$j,'utf-8');
          if(mb_strwidth($next_new,'utf-8')<$blankNum) continue;
          else{
            $m = $i+1;
            $result[] = $new.'<BR>';
            $j=1;
          }
        }
      }
    }
    $head = '';
    foreach ($result as $value) {
      $head .= $value;
    }
    if(strlen($price) < $B){
          $k1 = $B - strlen($price);
          for($q=0;$q<$k1;$q++){
                $kw1 .= ' ';
          }
          $price = $price.$kw1;
    }
    if(strlen($num) < $C){
          $k2 = $C - strlen($num);
          for($q=0;$q<$k2;$q++){
                $kw2 .= ' ';
          }
          $num = $num.$kw2;
    }
    if(strlen($prices) < $D){
          $k3 = $D - strlen($prices);
          for($q=0;$q<$k3;$q++){
                $kw4 .= ' ';
          }
          $prices = $prices.$kw4;
    }
    $orderInfo .= $head.$tail.' '.$price.' '.$num.' '.$prices.'<BR>';
    //@$nums += $prices;
    }
    $time = date('Y-m-d H:i:s',time());
    $orderInfo .= '--------------------------------<BR>';
    return $orderInfo;
}

/*
 * 获取两地之间最短距离几米
 * $lat1=0,起点纬度
 * $lng1=0,起点经度
 * $lat2=0,终点纬度
 * $lng2=0,终点经度
 */
function getDistance($lat1=0,$lng1=0,$lat2=0,$lng2=0)
{
    $ak = '4IU3oIAMpZhfWZsMu7xzqBBAf6vMHcoa';//您的百度地图ak，可以去百度开发者中心去免费申请
    $distance = array();
    $distance['distance'] = 0.00;//距离 公里
    $distance['duration'] = 0.00;//时间 分钟
    $url = 'http://api.map.baidu.com/routematrix/v2/driving?output=json&origins='.$lat1.','.$lng1.'&destinations='.$lat2.','.$lng2.'&ak='.$ak;
    $data = file_get_contents($url);
    $data = json_decode($data,true);
//		var_dump($data['result'][0]['distance']);die;
    if (!empty($data) && $data['status'] == 0) {

        $distance =$data['result'][0]['distance']['value']; //计算距离
    }else{
        return false;
    }
    return $distance;
}

function getTimesf($time)
{
    if(!is_array($time))return false;

    $arr = [];
    foreach($time as $k=>&$v){
        $times = explode(':', $v);
        $arr[$k] = intval($times[0])*60*60+intval($times[1])*60;
    }
    return $arr;
}

/*
 * 获取配送时间
 */
function getSendtime($paytime,$route_id)
{
    if(!isset($paytime))return false;
    if(!isset($route_id))return false;
    $sel = db('route')->where(['id'=>$route_id])->find();
//    $paytime = time();//下单时间
    $y = date('Y',$paytime);
    $m = date('m',$paytime);
    $d = date('d',$paytime);

    //线路每天几点送
    if(!empty($sel['every_time'])){
        $every_time_stamp = unserialize($sel['every_time']);
        $every_time_stamp = getTimesf($every_time_stamp);
        sort($every_time_stamp,SORT_NUMERIC);
       // var_dump($every_time_stamp);die;

    }
    //线路每个几天送
    if(!empty($sel['every_day'])){
        $send_time = db('order')->where('route_id='.$route_id)->max('send_time');
        if($send_time){
            if(TIMESTAMP<$send_time){//下单时间<已有配送时间
                $count_days = 0;
            }else{//下单时间>已有配送时间,计算他隔几天配送
                $dif = (TIMESTAMP-$send_time);
           // var_dump($dif);
                if($dif<86400){//小于一天
                    $count_days = 1;
                }else {
                    $diff = $dif / 86400;//几天
                    if($diff<$sel['every_day']){
                        $count_days = 1;
                    }else{
                        $a_days = ($diff/$sel['every_day']);
                        $count_days = ceil($a_days);
                    }
                }
            }
            $send_time = $send_time + 86400 *$count_days;
        }else{
            if(!empty($sel['every_time'])){
                $send_time = strtotime(date('Y-m-d',time()))+24*60*60*$sel['every_day']+$every_time_stamp[0];
            }else{
                $send_time = strtotime(date('Y-m-d',time()))+24*60*60*$sel['every_day'];
            }
        }
    }
    //几号送
    if(!empty($sel['days'])){
        $days=explode(',',$sel['days']);
        $send_time_d = 0;
		// var_dump($m);
		// var_dump($days);
		// var_dump($y);
		// die;
        foreach($days as $k=>$v){
            $dis = $days[$k]-$d;
            $check = checkdate($m,$days[$k],$y);
            if($dis>0 && $check){
                $send_time_d = $v;
                break;
            }
        }

        if(empty($send_time_d)){
            $send_time_d = $days[0];
            $m = $m+1;
            if($m>12){
                $m = 1;
                $y = $y+1;
            }
        }

        $send_time_str = $y.'-'.$m.'-'.$send_time_d;
        if(!empty($sel['every_time'])){
            $send_time = strtotime($send_time_str) + $every_time_stamp[0];
        }else{
            $send_time = strtotime($send_time_str);
        }
    }
    if(!empty($sel['every_time']) && empty($sel['days']) && empty($sel['every_day'])){
//        echo 'c';
        $send_time_str = $y.'-'.$m.'-'.$d;
        foreach($every_time_stamp as $kk=>$vv){
            $send_time = strtotime($send_time_str) + $every_time_stamp[$kk];
            if($send_time>TIMESTAMP){
                $send_time = $send_time;
                $is_no = 0;
                break;
            }else{
                $is_no = 1;
            }
        }
        if($is_no == 1){
            $send_time = strtotime($send_time_str) + $every_time_stamp[0]+60*60*24;
        }
    }
    //线路每天送
    if($sel['every_day'] == 0 && empty($sel['every_time'])){
        if(!empty($sel['every_time'])){
            $send_time = strtotime(date('Y-m-d',time()))+$every_time_stamp;
        }else{
            $send_time = strtotime(date('Y-m-d',time()))+24*60*60;
        }
        if($send_time<time()){
            $send_time = $send_time+24*60*60;
        }
    }
    return $send_time;
}

